package springboot.consumer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.xq.softcup.mq.client.consumer.IMqConsumer;
import org.xq.softcup.mq.client.consumer.annotation.MqConsumer;
import org.xq.softcup.mq.client.util.MqResult;
import springboot.producer.Contants;

@MqConsumer(topic = "topic_order", group = MqConsumer.EMPTY_GROUP)
@Service
public class ConsumerC implements IMqConsumer {
    private Logger logger = LoggerFactory.getLogger(ConsumerC.class);

    @Override
    public MqResult consume(String data) throws Exception {
//        logger.info("消费一条消息:{}", data);
        Contants.TOTAL.addAndGet(1);
        if (Contants.TOTAL.get() == 1) {
            Contants.START_TIME = System.currentTimeMillis();
        } else if (Contants.TOTAL.get()%10000 == 0) { //每一万条数据，显示一下接收条数和耗时
            //获取当前结束时间
            Contants.END_TIME = System.currentTimeMillis();
            //计算耗时
            long spend = Contants.END_TIME - Contants.START_TIME;
            Contants.TIME_SPEND += spend; //耗时累计
            logger.info("所有topic_order消费者接收消息:{}条，耗时:{} ms", Contants.TOTAL.get(), spend);
            //重设开始时间
            Contants.START_TIME = System.currentTimeMillis();
        }
        //如果接收的数量和发送的数量相等，则重置接收的数量
        if (Contants.TOTAL.get() >= Contants.COUNT) {
            logger.info("接收{}条消息，共耗时:{} ms, 平均耗时:{} ms(每万条)", Contants.TOTAL.get(), Contants.TIME_SPEND, (Contants.TIME_SPEND/(Contants.COUNT/10000f)));
            Contants.TOTAL.set(0); //重置接收计数器
            Contants.TIME_SPEND = 0l;//重置累计耗时
        }
        return MqResult.SUCCESS;
    }

}
